<script setup lang="ts">
import axios from "axios";
import { ref, onMounted, watch } from "vue";
import type { ComponentSize } from "element-plus";
import { ElMessage } from "element-plus";

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const size = ref<ComponentSize>("default");
const background = ref(true);
const disabled = ref(false);

// 表格数据
const tableData = ref([]);

// 搜索相关
const search = ref({
  serviceId: null,
  custName: null,
  questionType: null,
  state: null,
  grade: null,
  score: null,
});

function handleSearch() {
  loadData();
  // 如果需要请求后端，可以在这里发请求
}

function resetSearch() {
  search.value = {
    serviceId: null,
    custName: null,
    questionType: null,
    state: null,
    grade: null,
    score: null,
  };
  loadData();
}

// 售后服务处理弹窗相关
const dialogVisible = ref(false);
const editForm = ref({
  afterSaleId: null,
  content: null,
  // 其它字段...
});

// 售后服务处理详情
const table = ref(false);

const gridData = ref(null);

// 监听分页变化，自动加载数据
watch([currentPage, pageSize], () => {
  loadData();
});

// 页面首次加载
onMounted(() => {
  loadData();
});

// 获取回复消息列表
function getAfterSaleReply(afterSaleId) {
  gridData.value = null;
  axios
    .get(`http://localhost:52010/after-sale/reply/service/${afterSaleId}`)
    .then((response) => {
      const res = response.data;
      if (res.code === 200) {
        console.log(res.data);
        // 处理回复消息列表
        gridData.value = response.data.data;
      } else {
        ElMessage.error(res.message || "请求失败");
      }
    });
}

// 点击“详情”按钮
function handleDetail(row) {
  // 复制 row 数据（推荐深拷贝，防止直接修改表格数据）
  console.log(row);
  table.value = true;
  // 获取回复消息列表
  getAfterSaleReply(row.serviceId);
}

// 点击“处理”按钮
function handleDispose(row) {
  // 复制 row 数据（推荐深拷贝，防止直接修改表格数据）
  console.log(row);
  dialogVisible.value = true;
  editForm.value.afterSaleId = row.serviceId;
  console.log("editForm.value.afterSaleId:" + editForm.value.afterSaleId);
}

// 提交修改
function submitEdit() {
  axios
    .post(`http://localhost:52010/after-sale/reply`, editForm.value)
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success("回复成功");
        dialogVisible.value = false;
        loadData(); // 编辑成功后刷新表格
      } else {
        ElMessage.error(res.data.message || "回复失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.response?.data?.message || err.message || "请求异常");
    });
}

// 重置表单
function resetEditForm() {
  editForm.value = {
    afterSaleId: null,
    content: null,
  };
}

function loadData() {
  // 你的后端接口如果是 /customer/page/1/5 这样的
  const url = `http://localhost:52010/after-sale/page/${currentPage.value}/${pageSize.value}`;

  // 只传递有值的搜索条件
  const params = {};
  Object.keys(search.value).forEach((key) => {
    if (search.value[key]) {
      params[key] = search.value[key];
    }
  });

  axios
    .get(url, { params })
    .then((response) => {
      const res = response.data;
      if (res.code === 200) {
        tableData.value = res.data.records || [];
        total.value = res.data.total || 0;
      } else {
        ElMessage.error(res.message || "请求失败");
      }
    })
    .catch((error) => {
      const msg = error.response?.data?.message || error.message || "请求异常";
      ElMessage.error(msg);
    });
}

// 可选：分页事件处理器
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 改变pageSize时重置到第一页
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};
</script>

<template>
  <h2>售后服务记录</h2>
  <!-- 搜索部分 -->
  <div style="margin-bottom: 10px; display: flex; gap: 8px">
    <el-input
      v-model="search.serviceId"
      placeholder="服务编号"
      size="small"
      style="width: 100px"
    />
    <el-input
      v-model="search.custName"
      placeholder="客户名"
      size="small"
      style="width: 100px"
    />
    <el-input
      v-model="search.questionType"
      placeholder="问题类型"
      size="small"
      style="width: 100px"
    />
    <el-input
      v-model="search.state"
      placeholder="服务状态"
      size="small"
      style="width: 100px"
    />
    <el-select
      v-model="search.grade"
      placeholder="服务等级"
      size="small"
      style="width: 100px"
    >
      <el-option label="1" :value="1" />
      <el-option label="2" :value="2" />
      <el-option label="3" :value="3" />
      <el-option label="4" :value="4" />
    </el-select>
    <el-select
      v-model="search.score"
      placeholder="服务评分"
      size="small"
      style="width: 100px"
    >
      <el-option label="1" :value="1" />
      <el-option label="2" :value="2" />
      <el-option label="3" :value="3" />
      <el-option label="4" :value="4" />
      <el-option label="5" :value="5" />
    </el-select>
    <el-button type="primary" size="small" @click="handleSearch"
      >查找</el-button
    >
    <el-button size="small" @click="resetSearch">重置</el-button>
  </div>

  <el-table :data="tableData" style="width: 100%">
    <!-- 表格 -->
    <el-table-column fixed prop="serviceId" label="服务编号" />
    <el-table-column prop="custName" label="客户名" />
    <el-table-column prop="itemName" label="产品名" />
    <el-table-column prop="questionType" label="问题类型" />
    <el-table-column prop="state" label="服务状态" />
    <el-table-column prop="grade" label="服务等级" />
    <el-table-column prop="score" label="服务评分" />
    <el-table-column fixed="right" label="操作" min-width="100">
      <template #default="scope">
        <el-button
          link
          type="primary"
          size="small"
          @click="handleDetail(scope.row)"
        >
          详情
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="handleDispose(scope.row)"
          >处理</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 处理售后服务对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="添加回复"
    width="500px"
    @close="resetEditForm"
  >
    <div class="form-center">
      <el-form :model="editForm" label-width="auto" style="min-width: 400px">
        <el-form-item label="回复信息">
          <el-input v-model="editForm.content" type="textarea" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 售后服务详情抽屉 -->
  <el-drawer v-model="table" title="回复信息列表" direction="rtl" size="80%">
    <el-table :data="gridData">
      <el-table-column property="id" label="信息编号" width="90" />
      <el-table-column property="content" label="内容" />
      <el-table-column property="state" label="状态" width="90" />
      <el-table-column property="replyTime" label="发送时间" width="100" />
      <el-table-column property="empId" label="回复人编号" width="100" />
    </el-table>
  </el-drawer>

  <!-- 分页组件 -->
  <div class="pagination-block">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 30]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
.pagination-block {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 10px; /* 距离上方10px */
}
</style>